<template>
  <a-card title="用户列表">
    <template #extra>
      <a-button @click="handleCreate">添加用户</a-button>
    </template>
    <a-input-search v-model:value="keyword"
                    allow-clear
                    enter-button
                    placeholder="根据用户名检索"
                    style="width: 30%"
                    @search="onSearch"></a-input-search>
    <a-divider type="horizontal"/>
    <a-table :columns="columns"
             :data-source="userList"
             :pagination="pagination"
             :row-key="record => record._id" @change="handleTableChange">
      <template #createAt="{record}">
        {{ formatDate(record.meta.createAt) }}
      </template>
      <template #authority="{record}">
        {{ getRoleById(record.roleId).title }}
        <a href="javascript:" @click="onEdit(record)">
          <EditOutlined/>
        </a>
      </template>
      <template #action="{ record }">
        <a-popconfirm title="确定要删除吗?" @confirm="onDelete(record)">
          <a-button type="link">删除</a-button>
        </a-popconfirm>
        <a-divider type="vertical"/>
        <a-popconfirm title="确定要重置密码吗?" @confirm="onReset(record)">
            <a-button type="link">重置密码</a-button>
        </a-popconfirm>
      </template>
    </a-table>
  </a-card>
  <a-modal
    v-model:visible="userFormVisible"
    :confirm-loading="confirmLoading"
    title="添加用户"
    @ok="createData"
  >
    <a-form :label-col="{span: 7}" :model="formState" :wrapper-col="{span: 11}">
      <a-form-item label="账号">
        <a-input v-model:value="formState.account"/>
      </a-form-item>
      <a-form-item label="密码">
        <a-input v-model:value="formState.password"/>
      </a-form-item>
      <a-form-item label="角色">
        <a-select v-model:value="formState.roleId" placeholder="请选择角色">
          <a-select-option v-for="item in roleList"
                           :key="item._id"
                           :value="item._id">{{ item.title }}
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
  <a-modal v-model:visible="roleFormVisible" title="修改角色" @ok="updateRoleId">
    <a-select v-model:value="roleForm.roleId" style="width: 50%">
      <a-select-option v-for="item in roleList" :key="item._id" :value="item._id">
        {{ item.title }}
      </a-select-option>
    </a-select>
  </a-modal>
</template>

<script>
import { Button, Card, Divider, Form, Input, message, Modal, Popconfirm, Select, Table } from 'ant-design-vue'
import { computed, onMounted, reactive, ref } from 'vue'
import { createUser, deleteUser, fetchUserList, resetPassword } from '@/api/user'
import { deepClone, formatDate, getRoleById } from '../../utils'
import store from '@/store/index'
import { EditOutlined } from '@ant-design/icons-vue'
import { updateRole } from '@/api/role'

const defaultFormState = {
  account: '',
  password: '',
}

const columns = [
  {
    title: '账户',
    dataIndex: 'account',
    key: 'account',
  },
  // {
  //   title: '是否被邀请',
  //   dataIndex: 'isInvited',
  //   key: 'isInvited',
  // },
  {
    title: '权限',
    slots: {
      customRender: 'authority',
    },
    key: 'authority',
  },
  {
    title: '创建时间',
    slots: {
      customRender: 'createAt',
    },
    key: 'createAt',
  },
  {
    title: '操作',
    key: 'action',
    slots: {
      customRender: 'action',
    },
  },
]

export default {
  name: 'index',
  components: {
    ACard: Card,
    ATable: Table,
    ADivider: Divider,
    AButton: Button,
    APopconfirm: Popconfirm,
    AModal: Modal,
    AForm: Form,
    AFormItem: Form.Item,
    AInput: Input,
    ASelect: Select,
    ASelectOption: Select.Option,
    AInputSearch: Input.Search,
    EditOutlined,
  },
  setup () {
    const userList = ref([])
    const currentPage = ref(1)
    const size = ref(5)
    const total = ref(0)
    const confirmLoading = ref(false)
    const modalText = ref('Content of the modal')
    const userFormVisible = ref(false)
    const roleFormVisible = ref(false)
    const formState = reactive({
      account: '',
      password: '',
      roleId: '',
    })
    const roleForm = reactive({
      userId: '',
      roleId: '',
    })
    const { roleList } = store.state
    formState.roleId = roleList[1]._id
    const keyword = ref('')
    const pagination = computed(() => ({ // 此处意为：直接返回一个对象，小括号是优先级的意思，先执行小括号内部的
        total: total.value,
        current: currentPage.value,
        pageSize: size.value,
      }),
    )
    const handleTableChange = async ({ current, pageSize }) => {
      currentPage.value = current
      size.value = pageSize
      await getList()
    }

    const getList = async () => {
      fetchUserList(currentPage.value, size.value, keyword.value)
        .then(res => {
            userList.value = res.data.list
            total.value = res.data.total
          },
        )
    }

    onMounted(() => {
        getList()
      },
    )
    const handleCreate = () => {
      userFormVisible.value = true
    }

    const onReset = async record => {
      await resetPassword(record._id).then(
        res => {
          message.success(res.msg)
        },
      )
    }

    const onSearch = async () => {
      await getList()
    }

    const createData = async () => {
      const temp = deepClone(formState)
      confirmLoading.value = true
      await createUser(temp).then(res => {
          userFormVisible.value = false
          confirmLoading.value = false
          message.success(res.msg)
        },
      )
      await getList()
      Object.assign(formState, defaultFormState)
    }

    const onDelete = record => {
      const index = userList.value.findIndex(element => element._id === record._id)
      deleteUser(record._id).then(res => message.success(res.msg))
      userList.value.splice(index, 1)
    }

    const onEdit = record => {
      roleFormVisible.value = true
      roleForm.userId = record._id
      roleForm.roleId = record.roleId
    }

    const updateRoleId = async () => {
      await updateRole(roleForm).then(res => {
        message.success(res.msg)
        roleFormVisible.value = false
      })
      await getList()
    }

    return {
      columns,
      userList,
      userFormVisible,
      roleFormVisible,
      roleForm,
      modalText,
      confirmLoading,
      formState,
      pagination,
      keyword,
      handleTableChange,
      handleCreate,
      createData,
      updateRoleId,
      onDelete,
      onReset,
      onSearch,
      onEdit,
      formatDate,
      roleList,
      getRoleById,
    }
  },
}
</script>

<style scoped>

</style>
